package com.manlitech.cloudboot.oauth.config.handler;

import com.alibaba.fastjson.JSONObject;
import com.manlitech.cloudboot.common.enums.ResultEnums;
import com.manlitech.cloudboot.common.utils.Result;
import com.manlitech.cloudboot.common.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 无权访问
 * @author shensg
 * @date 2021/7/7 17:43
 */

@Component
@Slf4j
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    Logger logger = LoggerFactory.getLogger(MyAccessDeniedHandler.class);

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        Result result = ResultUtil.error(ResultEnums.ERROR_PERMISSION.getCode(),ResultEnums.ERROR_PERMISSION.getMsg());
        logger.error(JSONObject.toJSONString(result));
        out.write(JSONObject.toJSONString(result));
    }
}
